extends Node

# 玩家管理器 - 处理玩家的动态生成和场景切换

# 玩家场景资源
const PLAYER_SCENE = preload("res://player/player.tscn")

# 当前玩家实例
var current_player: CharacterBody2D = null

# 玩家数据（用于场景切换时保持状态）
var player_data = {
	"position": Vector2.ZERO,
	"direction": "down",
	"can_move": true,
	"is_first_spawn": true,  # 标记是否为首次生成
	"battle_speed_multiplier": 1.0,  # 战斗速度倍数
	"auto_encounter_enabled": false,  # 自动遇怪状态
	"previous_battle_speed": 1.0  # 自动遇怪前的战斗速度
}

# 默认生成位置
var default_spawn_position: Vector2 = Vector2(320, 320)

func _ready():
	# 设置为自动加载单例
	process_mode = Node.PROCESS_MODE_ALWAYS
	
	# 监听场景切换
	get_tree().tree_changed.connect(_on_scene_changed)

func _on_scene_changed():
	# 场景切换时清理当前玩家引用（但不自动生成新玩家）
	# 让各个场景脚本自己决定何时生成玩家
	pass

# 在当前场景生成玩家
func spawn_player_in_current_scene(spawn_position: Vector2 = Vector2.ZERO):
	# 等待场景完全加载
	await get_tree().process_frame
	
	var current_scene = get_tree().current_scene
	if current_scene == null:
		return
	
	# 如果已有玩家，先移除
	if current_player != null and is_instance_valid(current_player):
		save_player_data()
		current_player.queue_free()
		current_player = null
	
	# 创建新的玩家实例
	current_player = PLAYER_SCENE.instantiate()
	
	# 设置玩家位置
	if spawn_position != Vector2.ZERO:
		current_player.position = spawn_position
		current_player.target_position = spawn_position
		# 同时更新player_data中的位置
		player_data["position"] = spawn_position
	else:
		# 优先使用保存的位置，如果没有则使用默认位置
		var pos = player_data.get("position", Vector2.ZERO)
		if pos == Vector2.ZERO:
			pos = default_spawn_position
		current_player.position = pos
		current_player.target_position = pos
		# 确保player_data中的位置也是最新的
		player_data["position"] = pos
		print("[PlayerManager] 玩家生成位置: ", pos, " (来源: ", "保存数据" if player_data.get("position", Vector2.ZERO) != Vector2.ZERO else "默认位置", ")")
	
	# 如果是首次生成玩家，添加初始装备
	if player_data.get("is_first_spawn", true):
		_add_starter_equipment()
		player_data["is_first_spawn"] = false
	
	# 恢复玩家状态
	restore_player_data()
	
	# 将玩家添加到场景
	current_scene.add_child(current_player)
	
	# 玩家生成完成

# 在指定位置生成玩家（用于传送门等）
func spawn_player_at_position(position: Vector2):
	if position != Vector2.ZERO:
		spawn_player_in_current_scene(position)
	else:
		push_error("尝试在零坐标生成玩家，使用默认位置代替")
		spawn_player_in_current_scene(default_spawn_position)

# 保存玩家数据
func save_player_data():
	if current_player != null and is_instance_valid(current_player):
		player_data["position"] = current_player.position
		player_data["direction"] = current_player.get_direction_suffix()
		player_data["can_move"] = current_player.can_move

# 恢复玩家数据
func restore_player_data():
	if current_player != null:
		# 确保玩家处于静止状态
		current_player.is_moving = false
		current_player.target_position = current_player.position
		# 恢复移动能力
		current_player.set_can_move(player_data.get("can_move", true))
		# 等待一帧确保sprite节点已准备好，然后播放idle动画
		await get_tree().process_frame
		if current_player != null and current_player.sprite != null:
			var direction = player_data.get("direction", "down")
			current_player.sprite.play("idle_" + direction)

# 为新玩家添加初始装备
func _add_starter_equipment():
	"""为新玩家添加初始装备套装"""
	if ItemManager and ItemManager.has_method("add_starter_equipment"):
		ItemManager.add_starter_equipment()
		print("已为新玩家添加初始装备")
	else:
		print("错误: 无法找到物品管理器或初始装备方法")

# 获取当前玩家
func get_current_player() -> CharacterBody2D:
	return current_player

# 设置默认生成位置
func set_default_spawn_position(position: Vector2):
	default_spawn_position = position

# 移除当前玩家
func remove_current_player():
	if current_player != null and is_instance_valid(current_player):
		save_player_data()
		current_player.queue_free()
		current_player = null

# 检查玩家是否存在
func has_player() -> bool:
	return current_player != null and is_instance_valid(current_player)

# 设置玩家移动能力
func set_player_can_move(can_move: bool):
	if current_player != null:
		current_player.set_can_move(can_move)
	player_data["can_move"] = can_move

# 获取玩家位置
func get_player_position() -> Vector2:
	if current_player != null:
		return current_player.position
	return Vector2.ZERO

# 设置玩家位置
func set_player_position(position: Vector2):
	if current_player != null:
		current_player.position = position
		current_player.target_position = position
	player_data["position"] = position

# 设置战斗速度倍数
func set_battle_speed_multiplier(multiplier: float):
	"""设置战斗速度倍数"""
	player_data["battle_speed_multiplier"] = multiplier
	print("战斗速度设置为: %sx" % multiplier)

# 获取战斗速度倍数
func get_battle_speed_multiplier() -> float:
	"""获取当前战斗速度倍数"""
	return player_data.get("battle_speed_multiplier", 1.0)

# 保存自动遇怪状态
func save_auto_encounter_state(enabled: bool, previous_speed: float):
	"""保存自动遇怪状态"""
	player_data["auto_encounter_enabled"] = enabled
	player_data["previous_battle_speed"] = previous_speed

func get_auto_encounter_enabled() -> bool:
	"""获取自动遇怪状态"""
	return player_data.get("auto_encounter_enabled", false)

func get_previous_battle_speed() -> float:
	"""获取自动遇怪前的战斗速度"""
	return player_data.get("previous_battle_speed", 1.0)